package com.qd.pandaparkflow.compment.park;

import cn.hutool.core.math.Money;
import com.qd.pandaparkflow.context.PriceContext;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.util.Optional;

/**
 * 按小时计费
 *
 * @author sjk
 */
@ConditionalOnProperty(prefix = "liteflow", name = "enable", havingValue = "true")
@LiteflowComponent(value = "byHourCmp")
@Slf4j
public class ByHourComponent extends NodeComponent {

    @Override
    public void process() throws Exception {
        double hours = 0;
        final PriceContext priceContext = this.getContextBean(PriceContext.class);
        final Long minutes = priceContext.getMinutes();
        Money allPriceBigDecimal = new Money(Optional.ofNullable(priceContext.getFinalOrderPrice()).orElse(new BigDecimal(0L)));
        Money finalOrderPriceBigDecimal = new Money(0L);
        BigDecimal unitPrice = priceContext.getUnitPrice();
        if (null == unitPrice || unitPrice.signum() < 1) {
            unitPrice = priceContext.getRules().get(0).getPrice();
        }
        Money unitPriceBigDecimal = new Money(unitPrice);

        long hour = minutes / 60;
        if (hour > 0) {
            Money hourMoney = new Money(hour);
            finalOrderPriceBigDecimal = finalOrderPriceBigDecimal.add(hourMoney.multiply(unitPriceBigDecimal.getAmount()));
            hours += hour;
        }
        long b = minutes % 60;
        if (b < 30) {
            finalOrderPriceBigDecimal = finalOrderPriceBigDecimal.add(unitPriceBigDecimal.divide(new BigDecimal(2), RoundingMode.HALF_UP));
            hours += 0.5;
        } else {
            finalOrderPriceBigDecimal = finalOrderPriceBigDecimal.add(unitPriceBigDecimal);
            hours += 1;
        }
        priceContext.setFinalOrderPrice(allPriceBigDecimal.add(finalOrderPriceBigDecimal).getAmount());
        priceContext.getPrintLog().add(MessageFormat.format("按小时计算，总分钟数为[{0}],折算小时数为[{1}],单价是[{2}]，当前金额[{3}]，总金额:[{4}]", priceContext.getMinutes(), hours, unitPrice, finalOrderPriceBigDecimal.getAmount().toPlainString(), priceContext.getFinalOrderPrice().toPlainString()));

    }
}